import cv2 as cv
video = 'vtest.avi'
capture = cv.VideoCapture(video)
fgbg = cv.createBackgroundSubtractorMOG2()

def Object_label(mask, threshold, img):
    seg = mask.copy()
    cnts = cv.findContours(seg, cv.RETR_EXTERNAL, cv.CHAIN_APPROX_SIMPLE)
    count = 0
    for i in cnts[1]:
        area = cv.contourArea(i)
        if area < threshold:
            continue
        count += 1
        rect = cv.boundingRect(i)
        print("X:{} Y:{} Length:{} Width:{}".format(rect[0], rect[1], rect[2], rect[3]))
        cv.drawContours(img, [i], -1, (0, 255, 0), 1)
        cv.rectangle(img, (rect[0], rect[1]), (rect[0] + rect[2], rect[1] + rect[3]), (0, 0, 255), 1)
        cv.putText(img, str(count), (rect[0], rect[1]), cv.FONT_HERSHEY_PLAIN, 0.5, (255, 255, 0))
    return count

while True:
    ret, source = capture.read()
    if not ret:
        break
    image = cv.pyrDown(source)
    fgMask = fgbg.apply(image)

    kernel = cv.getStructuringElement(cv.MORPH_RECT, (5, 5))
    morphImage_open = cv.morphologyEx(fgMask, cv.MORPH_OPEN, kernel, iterations=5)
    mask = fgMask - morphImage_open
    _, Mask = cv.threshold(mask, 30, 255, cv.THRESH_BINARY + cv.THRESH_OTSU)
    targetObject = Object_label(Mask, 20, image)

    print('{0} objects have been detected!' .format(targetObject))
    backGroundPic = fgbg.getBackgroundImage()
    foreGroundPic = image - backGroundPic
    cv.imshow('Source', image)
    cv.imshow('Background Pic', backGroundPic)
    cv.imshow('Foreground Pic', Mask)
    key = cv.waitKey(40)
    if key == 27:
        break

capture.release()
cv.destroyAllWindows()


